from django.http import Http404, HttpResponse
import simplejson
from axis4.service_monitor.models import ServiceCheck, ServiceCheckHistory
from axis4.service_monitor.views import ActualController, UnProtectedController
import models
import services

__author__ = 'isd'

class CheckController(UnProtectedController):
    def default_function(self, request, url, user, *parts):
        self.base_log.debug("Checking services status")
        for service_check in ServiceCheck.all():
            if services.Service.is_not_deleted(service_check.service):
                self.base_log.debug("Checking " + service_check.service.name)
                for check_impl in services.get_checks():
                    self.base_log.debug("Impl %d ? %d" % (service_check.check_type.code, check_impl.get_code()))
                    if service_check.check_type.code == check_impl.get_code():
                        status, reason = check_impl.perform_check(service_check.service)
                        ServiceCheckHistory(service_check = service_check, status = status, status_text = reason).put()
        return HttpResponse(simplejson.dumps({"success": True}))

    def list(self, request, url, user, *parts):
        return HttpResponse(simplejson.dumps({"success": True, "data": [check.to_dict() for check in models.CheckType.all()]}))

class ServiceController(ActualController):
    def list(self, request, url, user, *parts):
        return HttpResponse(simplejson.dumps({"success": True,
                                              "data": [
                                                    dict([(key, val) for key, val in service.to_dict().iteritems()] +
                                                         [("status", services.ObjectUtil.to_dict(services.Service.get_service_state(service)))])
                                                    for service in services.Service.collect_account_services(services.Account.get_account(user))
                                              ]}))

    def list_checks(self, request, url, user, method, service_id, *parts):
        service = services.Service.get_service(int(service_id))
        if not services.Account.check_service(services.Account.get_account(user), service):
            raise Http404
        return HttpResponse(simplejson.dumps({"success": True,
                                              "data": [
                                                    dict([(key, val) for key, val in service_check.to_dict().iteritems()] +
                                                         [("history", [history.to_dict()
                                                                       for history in services.Service.collect_service_checks_history(service_check)])
                                                         ])
                                                    for service_check in services.Service.collect_service_checks(service)
                                              ]}))

    def add(self, request, url, user, *parts):
        cs = request.POST["checks"].split(",")
        s = models.Service(name = request.POST["name"], url = request.POST["url"])
        s.put()
        a = services.Account.get_account(user)
        sa = models.ServiceAccount(service = s, account = a)
        sa.put()
        for c in cs:
            models.ServiceCheck(service = s, check_type = services.Service.get_check_type(int(c))).put()
        return HttpResponse(simplejson.dumps({"success": True, "data": s.to_dict()}))

    def delete(self, request, url, user, *parts):
        service = services.Service.get_service(int(request.POST["service"]))
        if not services.Account.check_service(services.Account.get_account(user), service):
            raise Http404
        services.Service.delete_service(service)
        return HttpResponse(simplejson.dumps({"success": True}))

    def edit(self, request, url, user, *parts):
        service = services.Service.get_service(int(request.POST["service"]))
        if not services.Account.check_service(services.Account.get_account(user), service):
            raise Http404
        cs = request.POST["checks"].split(",")
        service.name = request.POST["name"]
        service.url = request.POST["url"]
        service.put()
        services.Service.update_service_checks(service, [int(c) for c in cs])
        return HttpResponse(simplejson.dumps({"success": True, "data": service.to_dict()}))
